package com.wwj.core.wawa.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wwj.core.wawa.entity.*;
import com.wwj.core.wawa.entity.mapper.DeliverRecordDetailMapper;
import com.wwj.core.wawa.entity.mapper.DeliverRecordMapper;
import com.wwj.core.wawa.entity.mapper.PlayRecordMapper;
import com.wwj.core.wawa.entity.mapper.WawaMapper;
import com.wwj.core.wawa.service.IDeliverRecordService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by Auser on 2017/11/24.
 */
@Service
public class DeliverRecordServiceImpl implements IDeliverRecordService {

    @Resource
    private DeliverRecordMapper deliverRecordMapper;

    @Resource
    private DeliverRecordDetailMapper deliverRecordDetailMapper;

    @Resource
    private PlayRecordMapper playRecordMapper;

    @Resource
    private WawaMapper wawaMapper;

    @Override
    public Page<DeliverRecord> findByPage(Map<String, Object> params, int offset, int limit) throws Exception {
        PageHelper.offsetPage(offset, limit);
        return (Page<DeliverRecord>)deliverRecordMapper.findByPage(params);
    }

    @Override
    public void updateDeliverRecord(DeliverRecord deliverRecord) throws Exception {
        deliverRecordMapper.updateDeliverRecord(deliverRecord);

        List<DeliverRecordDetail> deliverRecordDetails = deliverRecordDetailMapper.selectDeliverRecordDetailsByDeliverRecordId(deliverRecord.getId());
        for(DeliverRecordDetail deliverRecordDetail : deliverRecordDetails) {
            PlayRecord playRecord = playRecordMapper.selectPlayRecordById(deliverRecordDetail.getPlayRecordId());
            if(playRecord != null) {
                if (deliverRecord.getStatus() == DeliverRecord.STATUS_SENDED) {
                    WaWaType waWaType = playRecord.getWaWaType();
                    List<WaWa> waWas = wawaMapper.selectWaWaByWaWaType(waWaType.getId());
                    playRecord.setWawaId(waWas.get(new Random().nextInt(waWas.size())).getId());
                    playRecord.setIsDeliver(PlayRecord.DELIVERING);
                } else if(deliverRecord.getStatus() == DeliverRecord.STATUS_RECEIVED) {
                    playRecord.setIsDeliver(PlayRecord.RECEIVED);
                } else if(deliverRecord.getStatus() == DeliverRecord.STATUS_REJECT) {
                    playRecord.setIsDeliver(PlayRecord.REJECT);
                }
                playRecordMapper.updatePlayRecord(playRecord);
            }
        }
    }

    @Override
    public List<DeliverRecordDetail> findDetail(Integer id) throws Exception {
        return deliverRecordDetailMapper.selectDeliverRecordDetailsByDeliverRecordId(id);
    }
}
